<?php

namespace Home\Controller;

use Think\Controller;

class CartController extends CommonController
{
    /***
     * 购物车首页加载
     */
    public function cart()
    {
        $Product = M('Product');
        $Cart = M('Cart');
        $id = $_SESSION['customer']['id'];
        $carts = $Cart->where("customer_id = '$id'")->select();
        foreach ($carts as &$cart) {
            $cart['child'] = $Product->where("id = '$cart[product_id]'")->find();
        }

        if(empty($carts)){
            $this->redirect('Cart/em');
        }

        $this->assign(compact('carts'));

        $this->display();
    }

    /***
     * 购物车货物新增
     */

    public function add()
    {
        $Cart = M('Cart');
        if (IS_AJAX) {

            $data['product_id'] = I('post.product_id');
            $data['customer_id'] = $_SESSION['customer']['id'];
            $carts = $Cart->where($data)->setInc('num', 1);
            if (!$_SESSION['customer']) {
                $info = array('status' => 0, 'msg' => '请登录');
            } else {
                if (!$carts) {
                    $Cart->add($data);
                }
                $info = array('status' => 1, 'msg' => '添加购物车成功');
            }
            $this->ajaxReturn($info);
        }
    }

    /***
     * 移出购物车
     */
    public function delete_cart()
    {
        $Cart = M('Cart');
        if (IS_AJAX) {
            $id = I('post.id');
            $Cart->where("id = '$id'")->delete();
        }
    }
    /***
     * 改变购物量
     */
    public function change(){
        $Cart = M('Cart');

        if(IS_AJAX){
            $id = I('post.id');
            $num = I('post.num');
            $Cart->where("id = '$id'")->setField('num',$num);
        }
    }
    /***
     * 增加数量
     */
    public function add_sum(){
        $Cart = M('Cart');
        if(IS_AJAX){
            $id = I('post.id');
            $Cart->where("id = '$id'")->setInc('num');
        }
    }

    /***
     * 减少数量
     */
    public function sub(){
        if(IS_AJAX){
            $id = I('post.id');
            $this->cart->where("id = '$id'")->setDec('num');
        }
    }

    /***
     * 加载空购物车页面
     */
    public function em()
    {
        $this->display();
    }

}